package com.apes.fn.ssm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.ssm.repository.CalculatedStateRepository;
import com.apes.fn.ssm.repository.StoreMemberModelsRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.query.ApesDao;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("calculatedStateService")
public class CalculatedStateService extends ApesDao {

    @Autowired
    private StoreMemberModelsRepository storeMemberModelsRepository;
    @Autowired
    private CalculatedStateRepository calculatedStateRepository;

    // 修改确认完成标记
    public void updateConfirmComplete() {
        calculatedStateRepository.exec("UPDATE MAS_CALCULATED_STATE SET CONFIRM_COMPLETE_MARK = 1, LAST_UPDATED_STAMP = SYSDATE ");
    }

    // 修改进入第二界面标记
    public void updateStepTwoMark() {
        calculatedStateRepository.exec("UPDATE MAS_CALCULATED_STATE SET STEP_TWO_MARK = 1, LAST_UPDATED_STAMP = SYSDATE ");
    }

    @Listener(topic = "ssm.calculatedStateService.updateState")
    public void updateState(SimpleRequest request) {
        Map getMap = request.getMap();
        AtomicReference sql = new AtomicReference("UPDATE MAS_CALCULATED_STATE SET ");
        getMap.forEach((k, v) -> {
            if (!k.toString().equals("LOCATION_ID")) sql.set(sql.get().toString() + k + "=" + v);
        });
        sql.set(sql.get().toString() + " WHERE LOCATION_ID = '" + getMap.get("LOCATION_ID") + "'");
        calculatedStateRepository.exec(sql.get().toString());
    }

    // 判断系统是否自动完成测算
    public List<Map> judgeDone(SimpleRequest request) {
        return calculatedStateRepository.judgeDone();
    }

    // 人员是否已经确认完成测算
    public List confirmComplete() {
        return calculatedStateRepository.findAll("SELECT CONFIRM_COMPLETE_MARK, TO_CHAR(LAST_UPDATED_STAMP, 'YYYY/MM/DD HH24:MI:SS') LAST_UPDATED_STAMP FROM MAS_CALCULATED_STATE WHERE ROWNUM = 1 ");
    }

    // 计算结果
    public List<Map> findAlls() {
        return SpringManager.getBean(CalculatedStateRepository.class).findAlls();
    }

    // 会员车型
    public Page<Map> stepDownload(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        String locationId = nodeO.getString("LOCATION_ID");
        List<Map> locationDevels = SpringManager.getBean(LocationRepository.class).stockCalcuLocationDevel(locationId);
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        if (locationDevels.size() == 0) return storeMemberModelsRepository.stepVipModelDownload(locationId, pageRequest);
        return storeMemberModelsRepository.stepVipModelDownloadF(locationId, locationId, pageRequest);
    }

    public /*Page<Map>*//*JSONArray*/Map stepTwoModelPro(SimpleRequest request) {
        JSONObject getJO = request.getJO();
//        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        JSONObject condition = getJO.getJSONObject("condition");
        String locationId = condition.getString("LOCATION_ID");
        String fittingMessageId = condition.getString("FITTING_MESSAGE_ID");
        List<Map> modelResults = modelSql(locationId, fittingMessageId, 0, 0);
      /*  List result = new ArrayList();
        result.add(MapUtil.mapper("body", MapUtil.mapper("content", modelResults)));*/
      JSONArray result = new JSONArray();
      JSONObject content = new JSONObject();
        content.put("content", modelResults);
        result.add(content);
        return /*result*/MapUtil.mapper("content", modelResults, "total", modelResults.size());
    }

    // 车型商品匹配
    public Page<Map> stepTwoModelPro2(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
//        Pageable pageable = PageRequest.of(getJO.getIntValue("page"), getJO.getIntValue("size"));
//        storeMemberModelsRepository.stepTwoModelPro(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
        String locationId = nodeO.getString("LOCATION_ID");
        String fittingMessageId = nodeO.getString("FITTING_MESSAGE_ID");
        int pageV = pageEmpty(getJO.get("page"));
        int size = sizeEmpty(getJO.get("size"));
        List<Map> modelResults = modelSql(locationId, fittingMessageId, pageV, size);
        int modelSize = this.modelSize(locationId, fittingMessageId);
        PageImpl page = new PageImpl<>(modelResults, pageRequest, modelSize);
        return page;
    }

    private List<Map> modelSql(String locationId, String fittingMessageId, int page, int size) {
//        String sql = "" +
//                "SELECT A.* " +
//                "  FROM (SELECT A.*, ROWNUM XH " + // /*+ USE_HASH(RCVFEE,p) */
//                "          FROM V_"+ locationId +"_SALES A " +
//                "         WHERE FITTING_MESSAGE_ID = '"+ fittingMessageId +"' and rownum <= 300000) A ";
//        if (page == 0) {
//            sql += " WHERE XH > " + page + " AND XH <= " + size;
//        } else {
//            sql += " WHERE XH > " + page * size + " AND XH <= " +  (page + 1) * size;
//        }
//      return find(sql);
        return find(/*sql*/"SELECT A.*, (SELECT NAME FROM MAS_PRODUCT J WHERE J.ID = A.PRODUCT_ID) PRODUCT_NAME FROM V_"  + locationId + "_SALES A WHERE FITTING_MESSAGE_ID = '" + fittingMessageId + "' and ROWNUM <= 300000 ");
    }

    private int modelSize(String locationId, String fittingMessageId) {
        String sql = "SELECT * FROM V_"  + locationId + "_SALES WHERE FITTING_MESSAGE_ID = '" + fittingMessageId + "' ";
        return find(sql).size();
    }

    // 计算排位
    public Page<Map> stepTwoQualifying(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        return storeMemberModelsRepository.stepTwoQualifying(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
    }

    // 销量
    public Page<Map> stepTwoSales(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        return storeMemberModelsRepository.stepTwoSales(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
    }

    // 会员覆盖率
    public Page<Map> stepTwoMemberCoverage(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        return storeMemberModelsRepository.stepTwoMemberCoverage(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
    }

    // 备货 SKU
    public Page<Map> stepTwoStockPro(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        return storeMemberModelsRepository.stepTwoStockPro(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
    }

    // 备货数量
    public Page<Map> stepTwoStockQty(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject nodeO = getJO.getJSONObject("data").getJSONObject("node");
        PageRequest pageRequest = PageRequest.of(pageEmpty(getJO.get("page")), sizeEmpty(getJO.get("size")));
        return storeMemberModelsRepository.stepTwoStockQty(nodeO.getString("LOCATION_ID"), nodeO.getString("FITTING_MESSAGE_ID"), pageRequest);
    }

    // 判断 page
    private int pageEmpty(Object param) {
        return StringUtils.isEmpty(param)?0:Integer.parseInt(param.toString()) - 1;
    }

    // 判断分页 size
    private int sizeEmpty(Object param) {
        return StringUtils.isEmpty(param)?50:Integer.parseInt(param.toString());
    }

    // 判断数据是否清空完毕
    public List queryClearComplete() {
        return storeMemberModelsRepository.queryClearComplete();
    }
}
